package com.tanhua.dubbo.api.Impl;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mogo.Movement;
import com.tanhua.model.mogo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private IdWorker idWorker;

    /**
     * 查看好友动态
     * @param id
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Movement> FindByFridends(Long id, Integer page, Integer pagesize) {
        //查询当前用户可见的好友列表
        Criteria criteria = Criteria.where("friendId").in(id);
        Query query = new Query(criteria).skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //获取动态id列表
        List<ObjectId> movementId = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);

        //分页查询相关动态数据
        Criteria criteria1 = Criteria.where("id").in(movementId);
        Query query1 = new Query(criteria1);
        List<Movement> movementList = mongoTemplate.find(query1, Movement.class);
        return movementList;
    }

    /**
     * 发布动态
     * @param movement
     */
    @Override
    public void movements(Movement movement) {
        try {
            //获取pid
            Long pid = idWorker.getNextId("movement");
            //设置pid
            movement.setPid(pid);
            //设置当前时间
            movement.setCreated(System.currentTimeMillis());
            //保存动态信息
            mongoTemplate.save(movement);
/*            //查询用户列表好友关系表，获取好友id
            Criteria criteria = new Criteria();
            criteria.where("userId").is(movement.getUserId());
            Query query = Query.query(criteria);
            List<Friend> friends = mongoTemplate.find(query, Friend.class);
            //将好友id存到好友时间线表中
            for (Friend friend : friends) {
                MovementTimeLine movementTimeLine = new MovementTimeLine();
                movementTimeLine.setMovementId(movement.getId());//动态id
                movementTimeLine.setFriendId(friend.getFriendId());//好友id
                movementTimeLine.setCreated(System.currentTimeMillis());//当前时间
                movementTimeLine.setUserId(movement.getUserId());//用户id
                mongoTemplate.save(movementTimeLine);
            }*/
           //异步查询用户列表好友，构建好友时间线表
            timeLineService.SaveMovementTimeLine(movement.getUserId(),movement);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询个人动态
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult FindByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = new Criteria();
        criteria.where("userId").is(userId);
        Query query = Query.query(criteria).skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,0,movements);
    }

    /**
     * 根据pid查询动态（动态推荐）
     * @param pids
     */
    @Override
    public List<Movement> findMovementByPids(List<Long> pids) {
        //根据pid查询动态
        Query query = Query.query(Criteria.where("pid").in(pids));
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return movementList;
    }

    /**
     * 随机推荐
     * @param counts
     * @return
     */
    @Override
    public List<Movement> randomMovements(Integer counts) {
        //设计统计参数
        TypedAggregation<Movement> aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(counts));
        //调用mongotemplate方法统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        return results.getMappedResults();
    }

    @Override
    public Movement FindById(String movementId) {
       return mongoTemplate.findById(movementId,Movement.class);
    }
}
